package com.nxy.cpfsfe.busi.bbatproc;

import java.util.Map;
import java.util.concurrent.TimeUnit;
import com.nxy.cpfsfe.cache.DbToParmToCache;
import com.nxy.cpfsfe.mybatis.pojo.ToParm;
import com.nxy.cpfsfe.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.adtec.starring.datapool.CompSDO;
import com.adtec.starring.datapool.EPOper;
import com.adtec.starring.exception.BaseException;
import com.adtec.starring.struct.dta.DtaInfo;
import com.nxy.cpfsfe.busi.btmgtsk.BatchSettlementProc;
import com.nxy.cpfsfe.mybatis.pojo.TeBatchReq;
import com.nxy.cpfsfe.service.CpfsService;
import com.nxy.cpfsfe.util.XmlUtil;
import com.nxy.cpfsfe.util.zookeeper.DistributedLock;
import com.nxy.cpfsfe.util.zookeeper.ZookeeperLockUtil;

/**
 * 批量业务异步处理业务
 * @author lcq
 *
 */
public class BatStlASrvBean implements CpfsService{
	private final static Logger LOGGER = LoggerFactory.getLogger(BatStlASrvBean.class);	
	/**
	 * 批量结算异步处理
	 */
	public  void doService(){
		
    	//zookeeper锁定此批次信息
		DistributedLock distributedLock = null;
		try {
			LOGGER.info("---------批量结算异步处理开始--------");
			//3秒内获取锁继续执行
			ToParm waitTimeToParm = DbToParmToCache.getToParm().get("zookeeper/waitTime");
			//默认10秒，如果数据库中未定义等待时间，按照默认时间来
			int waitTime = 10;
			if(waitTimeToParm != null){
				waitTime = Integer.valueOf(waitTimeToParm.getDataVal());
			}
			Thread.sleep(waitTime*1000);//延时10秒，确保同步先执行
			String tpId = DtaInfo.getInstance().getTpId();
			// 获取输入
			CompSDO inputSdo = (CompSDO) EPOper.getCompSDO(tpId, "ReqBody"); // 获取输入接口
			String bizMsg = (String) inputSdo.getValue("BizMsg")!=null?(String) inputSdo.getValue("BizMsg"):""; // 业务报文	
			LOGGER.info("业务报文数据bizMsg:[{}]",bizMsg);
			//生成业务map
			Map<String,String> map = XmlUtil.xml2Map(bizMsg);		
			LOGGER.debug("开始业务逻辑处理");		
			String batNo = StringUtil.trimObject(map.get("/root/MsgBody/StlSumInfo/BatNo"));
			String sndSysId = StringUtil.trimObject(map.get("/root/MsgHeader/SndSysId"));
			LOGGER.debug("报文请求系统编号：[{}]，批次信息：[{}]",sndSysId,batNo);
			distributedLock = ZookeeperLockUtil.getInstance().creaZooKeeperLock( sndSysId+"TeBatchReq"+batNo);

			if(distributedLock.tryLock(waitTime,TimeUnit.SECONDS)){
				//完成结算操作后，更新批量请求登记表,系统生成对账文件，并通知业务系统
				BatchSettlementProc baProc =BatchSettlementProc.getInstance();
				TeBatchReq tReq = baProc.queryTeBatchReq(sndSysId,batNo);
				if(tReq != null){
					baProc.handleABatchPoc(tReq);
				}
			}
		} catch (BaseException e) {
			LOGGER.error("异常信息为errcode:[{}].错误信息[{}]",e.getErrorCode(),e.getErrorDesc());
			LOGGER.error("批量结算异步处理失败",e);
		}catch(Exception e){
			LOGGER.error("批量结算异步处理失败",e);
		}finally {
			if(distributedLock != null){
				distributedLock.unlock();
			}
			LOGGER.info("---------批量结算异步处理结束--------");	
		}
		
	}
}
